﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace WSManager.Wpf
{
    public class RelayCommand : ICommand
    {
        readonly Func<Boolean> _canExecute;
        readonly Action _execute;

        public RelayCommand(Action execute, Func<bool> canExecute = null)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            this._execute = execute;
            this._canExecute = canExecute;
            if (this._canExecute == null)
                this._canExecute = () => { return true; };
        }
        public event EventHandler CanExecuteChanged
        {
            add
            {

                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {

                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(Object parameter)
        {
            return _canExecute();
        }

        public void Execute(Object parameter)
        {
            _execute();
        }
    }

    public class RelayCommand<T>: ICommand
    {
        readonly Func<Boolean> _canExecute;
        readonly Action<T> _execute;

        public RelayCommand(Action<T> execute, Func<bool> canExecute = null)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            this._execute = execute;
            this._canExecute = canExecute;
            if (this._canExecute == null)
                this._canExecute = () => { return true; };
        }
        public event EventHandler CanExecuteChanged
        {
            add
            {

                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {

                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(Object parameter)
        {
            return _canExecute();
        }

        public void Execute(Object parameter)
        {
            _execute((T)parameter);
        }
    }

}
